import {redirect, useNavigate} from "react-router";
import {DeleteLocation} from "~/lib/server";
import type {Route} from "./+types/delete";
import {ActionButton, AlertDialog, DialogTrigger} from "@adobe/react-spectrum";
import {refreshSidebarData} from "~/store";

export async function clientAction({ params }: Route.ActionArgs) {
  await DeleteLocation(params.locationId);
  return redirect("/locations/0");
}

export function DestroyLocation({location}: { location: Pick<Location, "id" | "name"> }) {
  const navigate = useNavigate();

  let onPrimaryAction = async () => {
    try {
      await DeleteLocation(String(location.id));
      refreshSidebarData();
      navigate("/locations/0");
    } catch (error) {
      console.error("删除位置失败:", error);
    }
  };

  return (
      <DialogTrigger>
        <ActionButton>删除</ActionButton>
        <AlertDialog
            variant="destructive"
            title={`删除 ${location.name}`}
            primaryActionLabel="确认"
            cancelLabel="取消"
            onPrimaryAction={onPrimaryAction}>
          确认删除？
        </AlertDialog>
      </DialogTrigger>
  );
}

